/*
 *Copyright 2021-2023 NERCIS
 *
 *Licensed under the Apache License, Version 2.0 (the "License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *Unless required by applicable law or agreed to in writing, software
 *distributed under the License is distributed on an "AS IS" BASIS,
 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *See the License for the specific language governing permissions and
 *limitations under the License.
 */

package cn.ac.nercis.pes.service.project.imported;

import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.project.ImportConflictDTO;
import cn.ac.nercis.pes.model.standard.SystemSpecialTargetSDTO;
import cn.ac.nercis.pes.repository.dal.project.SystemSpecialTargetRepository;
import cn.ac.nercis.pes.repository.model.project.SystemSpecialTargetDO;
import cn.ac.nercis.pes.service.utils.CheckFieldUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 系统特殊指标数据导入服务
 *
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public record SystemSpecialTargetImportService(SystemSpecialTargetRepository systemSpecialTargetRepository) {
    @Autowired
    public SystemSpecialTargetImportService {
    }

    public Result<List<ImportConflictDTO>> checkSpecialTargetData(@NonNull String systemId, List<SystemSpecialTargetSDTO> targets) {
        var sourceTargets = this.systemSpecialTargetRepository.findAllBySystemId(systemId);
        if (CollectionUtils.isEmpty(sourceTargets)) {
            return Result.success();
        }
        List<ImportConflictDTO> conflictData = targets.stream()
                .flatMap(st -> this.checkSpecialTargetData(st, sourceTargets).stream())
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        return Result.success(conflictData);
    }

    public Result<String> importSpecialTargetData(@NonNull String systemId, List<SystemSpecialTargetSDTO> targets, Boolean cover) {
        var sourceTargets = this.systemSpecialTargetRepository.findAllBySystemId(systemId);
        Result<String> result = Result.success();
        for (var target : targets) {
            result = this.importSpecialTargetData(systemId, target, sourceTargets, cover);
            if (!result.isSuccess()) {
                break;
            }
        }
        return result;
    }


    private List<ImportConflictDTO> checkSpecialTargetData(@NonNull SystemSpecialTargetSDTO importTarget, List<SystemSpecialTargetDO> sourceTargets) {
        var sourceTarget = sourceTargets.stream()
                .filter(st -> StringUtils.equals(st.getName(), importTarget.getName())
                        && st.getSpecialType() == importTarget.getSpecialType()
                        && StringUtils.equals(st.getLayerTargetId(),importTarget.getLayerTargetId()))
                .findFirst().orElse(null);
        if (Objects.isNull(sourceTarget)) {
            return Collections.emptyList();
        }
        return CheckFieldUtils.checkField(sourceTarget, importTarget);
    }

    private Result<String> importSpecialTargetData(String systemId, @NonNull SystemSpecialTargetSDTO importTarget, List<SystemSpecialTargetDO> sourceTargets, Boolean cover) {
        var sourceTarget = sourceTargets.stream()
                .filter(st -> StringUtils.equals(st.getName(), importTarget.getName())
                        && st.getSpecialType() == importTarget.getSpecialType()
                        && StringUtils.equals(st.getLayerTargetId(),importTarget.getLayerTargetId()))
                .findFirst().orElse(null);
        if (Objects.isNull(sourceTarget)) {
            return createSpecialTargetData(systemId, importTarget, sourceTargets);
        } else {
            return modifySpecialTargetData(sourceTarget, importTarget, cover);
        }
    }

    private Result<String> createSpecialTargetData(String systemId, SystemSpecialTargetSDTO importTarget,
                                                  List<SystemSpecialTargetDO> sourceTargets) {
        var systemTarget = toSpecialTarget(systemId,importTarget);
        systemTarget.setCreateTime(LocalDateTime.now());
        return Optional.of(systemTarget)
                .map(this.systemSpecialTargetRepository::save)
                .map(data -> {
                    sourceTargets.add(data);
                    return Result.success(data.getId());
                })
                .orElse(Result.failed(String.format("导入%s特殊指标创建失败", importTarget.getName())));
    }

    private Result<String> modifySpecialTargetData(SystemSpecialTargetDO sourceTarget, SystemSpecialTargetSDTO importTarget, Boolean cover) {
        sourceTarget.setTargetDesc(CheckFieldUtils.applyContent(sourceTarget.getTargetDesc(), importTarget.getTargetDesc(), cover));
        sourceTarget.setReasons(CheckFieldUtils.applyContent(sourceTarget.getReasons(), importTarget.getReasons(), cover));
        sourceTarget.setSort(CheckFieldUtils.applyContent(sourceTarget.getSort(), importTarget.getSort(), cover));
        sourceTarget.setKmTargetId(CheckFieldUtils.applyContent(sourceTarget.getKmTargetId(), importTarget.getReasons(), cover));
        sourceTarget.setKmApplyClaim(CheckFieldUtils.applyContent(sourceTarget.getKmApplyClaim(), importTarget.getReasons(), cover));
        sourceTarget.setKmDeepness(CheckFieldUtils.applyContent(sourceTarget.getKmDeepness(), importTarget.getKmDeepness(), cover));
        sourceTarget.setKmIsSpecial(CheckFieldUtils.applyContent(sourceTarget.getKmIsSpecial(), importTarget.getKmIsSpecial(), cover));
        sourceTarget.setKmScore(CheckFieldUtils.applyContent(sourceTarget.getKmScore(), importTarget.getKmScore(), cover));
        sourceTarget.setKmLevel(CheckFieldUtils.applyContent(sourceTarget.getKmLevel(), importTarget.getKmLevel(), cover));
        sourceTarget.setKmType(CheckFieldUtils.applyContent(sourceTarget.getKmType(), importTarget.getKmType(), cover));
        sourceTarget.setKmWeight(CheckFieldUtils.applyContent(sourceTarget.getKmWeight(), importTarget.getKmWeight(), cover));
        sourceTarget.setModifyTime(LocalDateTime.now());
        return Optional.of(sourceTarget)
                .map(this.systemSpecialTargetRepository::save)
                .map(SystemSpecialTargetDO::getId)
                .map(Result::success)
                .orElse(Result.failed(String.format("导入%s特殊指标修改失败", importTarget.getName())));
    }

    private SystemSpecialTargetDO toSpecialTarget(String systemId, SystemSpecialTargetSDTO importTarget){
        return SystemSpecialTargetDO.builder()
                .systemId(systemId)
                .name(importTarget.getName())
                .specialType(importTarget.getSpecialType())
                .targetDesc(importTarget.getTargetDesc())
                .reasons(importTarget.getReasons())
                .layerTargetId(importTarget.getLayerTargetId())
                .sort(importTarget.getSort())
                .kmTargetId(importTarget.getKmTargetId())
                .kmApplyClaim(importTarget.getKmApplyClaim())
                .kmDeepness(importTarget.getKmDeepness())
                .kmIsSpecial(importTarget.getKmIsSpecial())
                .kmScore(importTarget.getKmScore())
                .kmLevel(importTarget.getKmLevel())
                .kmType(importTarget.getKmType())
                .kmWeight(importTarget.getKmWeight())
                .build();
    }

}
